/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.frontendproject.generate;

import com.inspur.edp.web.common.constant.FrontendProjectConstant;
import com.inspur.edp.web.common.customexception.WebCustomException;
import com.inspur.edp.web.common.entity.TerminalType;
import com.inspur.edp.web.common.environment.EnvironmentException;
import com.inspur.edp.web.common.io.FileUtility;
import com.inspur.edp.web.common.metadata.GspProjectUtility;
import com.inspur.edp.web.common.utility.StringUtility;
import com.inspur.edp.web.frontendproject.FrontendProjectUtility;
import com.inspur.edp.web.jitengine.JITEngineManager;
import io.iec.edp.caf.commons.exception.ExceptionLevel;

/**
 * 前端工程执行babel 生成
 * @author  noah
 */
public class FrontendProjectGenerateForBabel {
    public static void generate(String projectPath) {
        projectPath = FrontendProjectUtility.getProjectPathWithDevRootPath(projectPath);

        if (StringUtility.isNullOrEmpty(projectPath)) {
            throw new WebCustomException("Current Project Path is Null or Empty", ExceptionLevel.Warning);
        }

        try {

            JITEngineManager.generateFrontendProjectForBabel(projectPath);

            // 生成后动作
            String babelProjectName = GspProjectUtility.getProjectName(projectPath) + "forbabel";
            String targetServiceProductPath = projectPath + "/src" + "/" + FrontendProjectConstant.PROJECT_GENERATE_PATH_FOR_BABEL + "/projects" + "/" + babelProjectName + "/src/app";
            String sourceServiceProductPath = java.nio.file.Paths.get(projectPath).resolve(TerminalType.PC.getServiceRelativePath()).toString();
            boolean isPathExists = FileUtility.exists(sourceServiceProductPath);
            if (isPathExists) {
                FileUtility.copyFolder(sourceServiceProductPath, targetServiceProductPath);
            }
        } catch (EnvironmentException ex) {
            throw new WebCustomException(ex.getMessage(), ex);
        } catch (RuntimeException exception) {
            throw new WebCustomException(String.format("Error When Generating a Frontend Project. Current Project Path is: %1$s。 %2$s", projectPath, exception.getMessage()), exception);
        }
    }
}
